<template>
  <EcDialog v-model="dialogVisible" class="form-dialog">
    <!-- 标题 -->
    <template #title>
      <div class="dialog-title">
        <SvgIcon :icon="dialogIconMap[dialogMode]"/>
        <span>{{ dialogModeMap[dialogMode] + ' - ' + dialogTitle }}</span>
      </div>
    </template>

    <!-- 表单数据 -->
    <el-form ref="formRef"
             v-loading="dataLoading"
             :disabled="readonly"
             :model="formData"
             :rules="formRules"
             class="full-form"
             label-width="auto"
             status-icon>

      <el-form-item label="名称：" prop="name">
        <el-input v-model="formData.name" placeholder="请输入角色名称"/>
      </el-form-item>

<!--      <el-form-item label="备注：" prop="remark">-->
<!--        <el-input v-model="formData.remark" :autosize="{ minRows: 2}" placeholder="请输入角色备注" type="textarea"/>-->
<!--      </el-form-item>-->

      <el-form-item label="授权：">
        <div v-if="menuData.length > 0">
          <el-button plain size="small" type="primary" @click="handleExpandCollapse">{{ menuExpand ? '收起' : '展开' }}</el-button>
          <el-button plain size="small" type="primary" @click="handleCheckedAll">{{ treeNodeAll ? '全不选' : '全选' }}</el-button>
        </div>
        <el-tree ref="menuTreeRef"
                 v-loading="menuTreeLoading"
                 :data="menuData"
                 :default-expand-all="menuExpand"
                 :expand-on-click-node="false"
                 :props="menuTreeProps"
                 check-strictly
                 class="permission-tree"
                 empty-text="暂无数据"
                 highlight-current
                 node-key="id"
                 show-checkbox
                 @check-change="handleCheckChange">
        </el-tree>
      </el-form-item>
    </el-form>

    <!-- 底部操作区域 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button :loading="dataLoading" @click="dialogVisible = false">取 消</el-button>
        <el-button v-if="!readonly" v-permission="['sys:role:create', 'sys:role:update']" :loading="dataLoading" type="primary" @click="onSubmitForm()">确 定</el-button>
      </span>
    </template>
  </EcDialog>
</template>

<script lang="ts" setup>
import {computed, nextTick, reactive, ref} from 'vue';
import { ElLoading, ElMessage, ElNotification, FormInstance, FormRules } from 'element-plus';
import {
  getMenuList,
  SysMenuData,
  sysMenuTreeList, sysRoleAdd,
  SysRoleData,
  sysRoleInfo,
  sysRoleSaveOrUpdate, sysRoleUpdate
} from '@/api/api-sys.ts';
import useDialog from '@/hooks/use-dialog.ts';
import { EcDialog } from '@/components/dialog';
import { SvgIcon } from '@/components/icon';

defineOptions({name: 'SysRoleForm'});

const formRef = ref<FormInstance>();
const formLoading = ref(false) // 表单是否加载中
const {dialogVisible, dialogTitle, dialogMode, dialogModeMap, dialogIconMap} = useDialog(false);

// 默认表单数据
let defaultForm: SysRoleData = {
  id: 0,
  name: '',
  // remark: '',
  tree: [],
  type:2
};

// 表单数据
const formData = ref({...defaultForm});

// 表单验证规则
const formRules = reactive<FormRules>({
  name: [{required: true, message: '名称不能为空', trigger: 'change'}],
});

/** 判断数据是否处于加载中 */
const dataLoading = computed(() => {
  return formLoading.value || menuTreeLoading.value;
})

/** 是否只读 */
const readonly = computed(() => {
  return dialogMode.value == 0;
});

/** 是否新增 */
const isCreate = ref();

const menuData = ref<SysMenuData[]>([]);
const menuTreeRef = ref();
const menuTreeProps = {
  label: 'title',
  children: 'child',
};
const menuTreeLoading = ref(false)
const reverseWithChild=(arr:any)=> {
  return arr.slice().reverse().map(item => {
    if (Array.isArray(item.child)) {
      item.child = reverseWithChild(item.child);
    }
    return item;
  });
}
/** 打开弹窗 */
const open = async (mode: number, row?: any) => {
  dialogMode.value = mode;
  dialogTitle.value = '角色权限';
  dialogVisible.value = true;
  // 重置表单
  resetForm();
  isCreate.value=row.id
  // 获取权限菜单数据
  menuTreeLoading.value = true
  try {
    const {body} = await getMenuList({
      action:'tree',
      // cate:'ADMIN_MENU'
    });
    // const {data} = await sysMenuTreeList();
    menuData.value = reverseWithChild(body)
  } finally {
    menuTreeLoading.value = false
  }

  // 加载信息
  if (row.id) {
    formLoading.value = true
    try {
      // 加载用户数据
      // const {data} = await sysRoleInfo(id)
      formData.value = row;
      console.log(formData.value,99)
      let data=JSON.parse(row.tree)
      // 设置选中
      nextTick(()=>{
          data?.forEach((menuId: number) => {
            console.log(menuId)
            menuTreeRef.value?.setChecked(menuId, true, false)
          })
      })
    } finally {
      formLoading.value = false
    }
  }
}
// 提供 open 方法，用于打开弹窗
defineExpose({open})

/** 表单提交 */
const emit = defineEmits(['success']);
const onSubmitForm = async () => {
  await formRef.value?.validate((valid, fields) => {
    if (!valid) {
      ElMessage({type: 'error', message: '请检查是否有必填项未完善',});
      return
    }

    const loading = ElLoading.service({
      lock: true,
      text: '正在提交中...',
      background: 'rgba(0, 0, 0, 0.2)'
    })

    // 提交数据
    formData.value.tree = [
      ...(menuTreeRef.value?.getCheckedKeys(false) as unknown as Array<number>), // 获得当前选中节点
      ...(menuTreeRef.value?.getHalfCheckedKeys() as unknown as Array<number>) // 获得半选中的父节点
    ]
    if(isCreate.value==undefined){

    sysRoleAdd(formData.value, {action:'add'}).then(response => {
      // 提示信息
      ElNotification({title: '成功', message: '操作完成', type: 'success', duration: 2000})
      // 发送操作成功的事件
      emit('success')
      // 隐藏窗口
      dialogVisible.value = false
    }).finally(() => loading.close())
    }else{
      sysRoleUpdate(formData.value, {action:'update'}).then(response => {
        // 提示信息
        ElNotification({title: '成功', message: '操作完成', type: 'success', duration: 2000})
        // 发送操作成功的事件
        emit('success')
        // 隐藏窗口
        dialogVisible.value = false
      }).finally(() => loading.close())
    }
  });
};

/** 展开和收起处理 */
const menuExpand = ref(true) // 展开/折叠
const handleExpandCollapse = () => {
  menuExpand.value = !menuExpand.value;

  const nodes = menuTreeRef.value?.store.nodesMap
  for (let item in nodes) {
    if (nodes[item].expanded === menuExpand.value) {
      continue
    }
    nodes[item].expanded = menuExpand.value
  }
}

/** 全选/全不选 */
const treeNodeAll = ref(false) // 全选/全不选
const handleCheckedAll = () => {
  treeNodeAll.value = !treeNodeAll.value;
  if (treeNodeAll.value) {
    // 获取所有节点的映射
    const nodes = menuTreeRef.value?.store.nodesMap;
    // 遍历所有节点，设置它们的选中状态
    for (let item in nodes) {
      if (nodes[item].checked) {
        continue
      }
      nodes[item].checked = true;
    }
  } else {
    menuTreeRef.value?.setCheckedNodes([])
  }
}

/** 当复选框被点击的时候触发 */
const handleCheckChange = (data: any, checked: boolean, indeterminate: boolean) => {
  // console.log(data, checked, indeterminate)
}

/** 重置表单 */
const resetForm = () => {
  menuExpand.value = true
  treeNodeAll.value = false

  // 重置表单数据
  formData.value = {...defaultForm};
  // 重置界面表单数据
  formRef.value?.resetFields();

  // 重置树形结构
  menuData.value = []
  menuTreeRef.value?.setCheckedKeys([]);
};

</script>

<style lang="scss" scoped>
.form-dialog {
  .el-checkbox-group .el-checkbox {
    float: left;
    width: 150px;
    padding-right: 10px;
    margin: 0;
  }

  .permission-tree {
    width: 100%;
  }
}
</style>
